﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Framework.MVC;
using FrontCenter.Models;
using System.Configuration;
using Framework.Common.Utils;

namespace FrontCenter.Controllers
{
    public class VerifyCodeController : AsyncControllerBase
    {
        #region Private

        private const string m_default = "Normal";
        private const string m_sms = "Mobile";
        private const string m_verifycode = "verifycode";

        private static readonly double m_fontSize = double.Parse(ConfigurationManager.AppSettings["VerifyCodeSize"]);
        private static readonly int m_height = int.Parse(ConfigurationManager.AppSettings["VerifyCodeHeight"]);
        private static readonly double m_minutes = double.Parse(ConfigurationManager.AppSettings["VerifyCodeMinutes"]);

        #endregion Private

        #region default

        public void NormalAsync()
        {
            HttpCookie verifyCodeCookie = Request.Cookies[m_verifycode];
            if (verifyCodeCookie!=null&&!string.IsNullOrWhiteSpace(verifyCodeCookie.Value))
            {
                DeleteVerifyCode d_model = new DeleteVerifyCode {
                    Resource = m_default,
                    VerifyCode = verifyCodeCookie.Value
                };
                InitModel(d_model);
            }
            NewVerifyCode model = new NewVerifyCode
            {
                Resource = m_default
            };
            InitModel(model);
        }

        public ActionResult NormalCompleted(string code, string value)
        {
            if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(value))
                return new EmptyResult();

            HttpCookie verifyCodeCookie = Request.Cookies[m_verifycode];
            if (verifyCodeCookie != null)
                verifyCodeCookie.Value = code;
            else
                verifyCodeCookie = new HttpCookie(m_verifycode, code);
            verifyCodeCookie.Expires = DateTime.Now.AddMinutes(m_minutes);
            Response.AppendCookie(verifyCodeCookie);
            return File(GraphicHelper.CreateCodeGraphic(value, m_fontSize, m_height), @"image/jpeg");
        }

        #endregion default

        #region 

        [AcceptVerbs(HttpVerbs.Post)]
        public void MobileAsync(string code)
        {
            NewVerifyCode model = new NewVerifyCode
            {
                Resource = m_sms,
                VerifyCode = code,
                LimitedCode = code,
                LimitedValue = Request.UserHostAddress
            };
            InitModel(model);
        }

        public ActionResult MobileCompleted(string code, string value)
        {
            return Json(!(string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(value)));
        }

        #endregion sms
    }
}
